from .OnlineHandler import OnlineHandler
from influxdb_client import InfluxDBClient, Point
from conf.env import infuxdb_url,org,token
import json



class Infuxdb(OnlineHandler):
    def __init__(self, obj, requestdata, id, test):
        self.obj = obj
        self.requestdata = requestdata
        self.userid = id
        self.test = test
        self.query = None
        self.bind_params = None
        self.newQuery = None
        self.curor = None
    def sqlprocess(self):
        request = self.requestdata
        if not self.test:
            namelist = {}
            for i in self.obj['parameter']:
                if self.requestdata.get(i["name"]):
                    if i["typed"] == 'int':
                        namelist.update({i["name"]: int(self.requestdata[i['name']])})
                    else:
                        namelist.update({i["name"]: self.requestdata[i['name']]})
            request = namelist

        query, bind_params = j.prepare_query(self.obj['sql'], request)
        newquery = query % tuple(bind_params)
        self.query = newquery
    def createCursor(self):
        self.curor = InfluxDBClient(url=infuxdb_url, token=token, org=org)

    def process(self):
        tables = self.curor.query_api().query(self.query,org)
        output = tables.to_json(indent=5)
        return json.loads(output)

